let app = require("express").Router();
let path = require('path');
let fs = require('fs');
let formidable = require('formidable');

app.post('/imgupdate', (req, res) => {
  let form = new formidable.IncomingForm();
  form.encoding = 'utf-8';
  form.uploadDir = path.join(__dirname + "../../../public/store");
  form.keepExtensions = true;//保留后缀
  form.maxFieldsSize = 2 * 1024 * 1024;
  //处理图片
  form.parse(req, function (err, fields, files) {
    let filename = files.file.name
    let nameArray = filename.split('.');
    let type = nameArray[nameArray.length - 1];
    let date = new Date();
    let time = "" + date.getFullYear() + (date.getMonth() + 1) + date.getDate() + date.getHours() + date.getMinutes();
    let random = Math.round(Math.random() * 10000000);
    let avatarName = time + random + '.' + type;
    let newPath = form.uploadDir + "/" + avatarName;
    fs.renameSync(files.file.path, newPath);  //重命名
    res.json({ url: "http://localhost:8888/store/" + avatarName })
  })
})

module.exports = app;
